#include "apue.h"
#include <sys/wait.h>

void pr_exit(int status) {
    if (WIFEXITED(status)) {
        printf("normal termination, exit status = %d\n", WEXITSTATUS(status));
    } else if (WIFSIGNALED(status)) {
        printf("abnormal termination, signal number = %d%s\n", WTERMSIG(status),
    #ifdef WCOREDUMP
        WCOREDUMP(status) ? "(core file generated)" : ""
    #else
        ""
    #endif
        );
    } else if(WIFSTOPPED(status)) {
        printf("child stopped, signal number = %d\n", WSTOPSIG(status));
    }
}

int main(int argc, char *argv[]) {
    pid_t pid;
    int status;

    if ((pid = fork()) < 0) {
        err_sys("fork error");
    } else if (pid == 0) { /* child */
        exit(7);
    }

    if (wait(&status) != pid) { /* wait for child */
        err_sys("wait error");
    }
    pr_exit(status);

    if ((pid = fork()) < 0) {
        err_sys("fork error");
    } else if (pid == 0) { /* child */
        abort(); /* child generate SIGABRT */
    }

    if (wait(&status) != pid) { /* wait for child */
        err_sys("wait error");
    }
    pr_exit(status);

    if ((pid = fork()) < 0) {
        err_sys("fork error");
    } else if (pid == 0) { /* child: divide by 0 generates SIGFPE */
        int c = 0;
        status /= c;
    }

    if (wait(&status) != pid) { /* wait for child */
        err_sys("wait error");
    }
    pr_exit(status);

    return 0;
}